﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Text;

namespace Core.Library
{
    public class CreateLogFiles
    {
        private readonly string _logFormat;
        private readonly string _errorTime;

        public CreateLogFiles()
        {
            _logFormat  = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + " ==> ";
            var sYear   = DateTime.Now.Year.ToString();
            var sMonth  = DateTime.Now.Month.ToString();
            var sDay    = DateTime.Now.Day.ToString();
            _errorTime  = sYear + sMonth + sDay;
        }
        public void ErrorLog(string sPathName, string sErrMsg)
        {
            var sw = new StreamWriter(sPathName + "\\Error_" + _errorTime + ".txt", true);
            sw.WriteLine(_logFormat + sErrMsg);
            sw.Flush();
            sw.Close();
        }
    }

    public class MetaKeyword
    {
        public static void AddMetaTag(Page page, string addTitle, string addDesc)
        {
            Control ctlTitle = page.Header.FindControl("mainTitle");
            if (ctlTitle != null)
            {
                string newTitle = addTitle != "" ? addTitle : "";
                ctlTitle.Controls.Clear();
                ctlTitle.Controls.Add(new LiteralControl(newTitle));
            }

            var ctlMetaDesc = page.Header.FindControl("metaDescription") as HtmlMeta;
            if (ctlMetaDesc != null)
            {
                ctlMetaDesc.Attributes["content"] = addDesc != "" ? addDesc : "";
            }
        }

        
        public static void AddMetaTag(Page page, string addTitle, string addDesc, string addKeyword)
        {
            Control ctlTitle = page.Header.FindControl("mainTitle");
            if (ctlTitle != null)
            {
                string newTitle = addTitle != "" ? addTitle : "";
                ctlTitle.Controls.Add(new LiteralControl(newTitle));
            }

            var ctlMetaDesc = page.Header.FindControl("metaDescription") as HtmlMeta;
            if (ctlMetaDesc != null)
            {
                ctlMetaDesc.Attributes["content"] = addDesc != "" ? addDesc : "";
            }

            var ctlKeywords = page.Header.FindControl("metaKeywords") as HtmlMeta;
            if (ctlKeywords != null)
            {
                if (!string.IsNullOrEmpty(addKeyword))
                    ctlKeywords.Attributes["content"] = addKeyword;
                else
                    ctlKeywords.Visible = false;
            }
        }

        public static void AddMetaTag(Page page, string addTitle, string addDesc, string addKeyword, string addNewKeyword)
        {
            Control ctlTitle = page.Header.FindControl("mainTitle");
            if (ctlTitle != null)
            {
                string newTitle = addTitle != "" ? addTitle : "";
                ctlTitle.Controls.Add(new LiteralControl(newTitle));
            }

            var ctlMetaDesc = page.Header.FindControl("metaDescription") as HtmlMeta;
            if (ctlMetaDesc != null)
            {
                ctlMetaDesc.Attributes["content"] = addDesc != "" ? addDesc : "";
            }

            var ctlKeywords = page.Header.FindControl("metaKeywords") as HtmlMeta;
            if (ctlKeywords != null)
            {
                if (!string.IsNullOrEmpty(addKeyword))
                    ctlKeywords.Attributes["content"] = addKeyword;
                else
                    ctlKeywords.Visible = false;
            }

            var ctlNewKeywords = page.Header.FindControl("metaNewKeywords") as HtmlMeta;
            if (ctlNewKeywords != null)
            {
                if (!string.IsNullOrEmpty(addNewKeyword))
                    ctlNewKeywords.Attributes["content"] = addNewKeyword;
                else
                    ctlNewKeywords.Visible = false;
            }
        }
        
        public static void AddFacebookMetaTag(Page page, string title, string content, string url, string image)
        {
            HtmlMeta fbTitle = page.Header.FindControl("fbTitle") as HtmlMeta;
            if (fbTitle != null)
            {
                fbTitle.Attributes["content"] = title;
            }
            HtmlMeta fbDescription = page.Header.FindControl("fbDescription") as HtmlMeta;
            if (fbDescription != null)
            {
                fbDescription.Attributes["content"] = content;
            }
            HtmlMeta fbImage = page.Header.FindControl("fbImage") as HtmlMeta;
            if (fbImage != null)
            {
                fbImage.Attributes["content"] = image;
            }
            HtmlMeta fbUrl = page.Header.FindControl("fbUrl") as HtmlMeta;
            if (fbUrl != null)
            {
                fbUrl.Attributes["content"] = url;
            }
        }
    }
     
    public class Utils
    {
        public static string SESSION_IS_LOGGED_IN = "session_is_logged_in";
        public static string SESSION_MING_ID      = "session_ming_id";
        public static string SESSION_USERNAME     = "session_username";        
        public static string SESSION_EMAIL        = "session_email";
        public static string SESSION_AVATAR       = "session_avatar";
        public static string SESSION_FULLNAME     = "session_fullname";
        public static string SESSION_CHECKSUM     = "session_checksum";

        public static string[] Tabs = { "IsPublished", "IsWaitingForPublish", "IsDraft", "IsReturned", "IsRemoved", "Round1", "Round2", "Round3" };

        public static string IsPublished = "IsPublished";
        public static string IsWaitingForPublish = "IsWaitingForPublish";
        public static string IsDraft = "IsDraft";
        public static string IsReturned = "IsReturned";
        public static string IsRemoved = "IsRemoved";
        public static string ControlId = "cId";
        public static string UserControlId = "ucId";
        public static string GroupId = "gId";
        public static string MenuId = "mId";
        public static string UserId = "uId";
        public static string Tab = "tab";
        public static string TypeId = "typeId";
        public static string Keyword = "k";
        public static string KName = "kname";
        public static string KEmail = "kemail";
        public static string Id = "id";
        public static string Action = "action";
        public static string ReturnUrl = "rUrl";
        public static string Status = "status";
        public static string Tag = "tag";
        public static string IsFeature = "isfeature";
        public static string Email = "email";
        public static string Name = "name";
        public static string Round = "round";
        public static string Order = "order";
        public static string Search = "tim-kiem";
        public static string Photos = "photos";
        public static string Image = "image";
        public static string h = "h";
        public static string w = "w";
        public static string x = "x";
        public static string y = "y";
        public static string Relation = "relation";
        public static string Content = "content";
        public static string UserName = "username";
        public static string StartDate = "sd";
        public static string EndDate = "ed";
        public static string Date = "date";
        public static string PageIndex = "pi";
        public static string PageSize = "ps";
        public static string CompanyId = "companyId";
        public static string Top = "top";
        public static string NewsTitle = "news_title";
        public static string AfamilyParam = "utm_source";

        /// <summary>
        /// Ngăn cách hàng nghìn, Math Round 0, 0 trả về "-"            
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string FormatView(int number)
        {
            string format;

            if (number == 0)
            {
                format = "-";
            }
            else
            {
                if (number >= 1000 || number <= -1000)
                {
                    format = String.Format("{0:0,0}", number);
                }
                else
                {
                    format = String.Format("{0:0}", number);
                }
            }

            try
            {
                format = format.Replace(",", ".");
            }
            catch { }

            return format;
        }


        public static int GetIdFromRequestString(string requestString, int defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString != null ? int.Parse(requestString) : defaultId;
        }

        public static long GetLongIdFromRequestString(string requestString, long defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString != null ? long.Parse(requestString) : defaultId;
        }

        public static string GetIdFromRequestString(string requestString, string defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString ?? defaultId;
        }

        public static bool GetIdFromRequestString(string requestString, bool defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString != null ? bool.Parse(requestString) : defaultId;
        }

        public static int GetStt(int dataItemIndex, int pageIndex, int pageSize)
        {
            return (pageSize * (pageIndex - 1) + dataItemIndex + 1);
        }        
        
        public static long BuildNewsID()
        {
            const string NewsID_FORMAT = "yyyyMMddHHmmssFFFF";
            return Convert.ToInt64(DateTime.Now.ToString(NewsID_FORMAT));
        }

        public class Photo
        {
            public static string GetSourceImage(string imagePath)
            {
                if (!string.IsNullOrEmpty(imagePath) && !imagePath.StartsWith("http"))
                {
                    imagePath = imagePath.TrimStart('/');

                    string format = "{0}/{1}";

                    return string.Format(format, Const.STORAGE_DOMAIN, imagePath);
                }
                return string.Empty;
            }

            public static string GetThumbImage_W(string imagePath, int imageWidth)
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    imagePath = imagePath.TrimStart('/');

                    string format = "{0}/thumb_w/{1}/{2}";

                    return string.Format(format, Const.STORAGE_DOMAIN, imageWidth, imagePath);
                }
                return string.Empty;
            }

            public static string GetThumbImage_Zoom(string imagePath, int imageWidth, int imageHeight)
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    imagePath = imagePath.TrimStart('/');
                    string format = "{0}/zoom/{1}_{2}/{3}";

                    return string.Format(format, Const.STORAGE_DOMAIN, imageWidth, imageHeight, imagePath);
                }
                return string.Empty;
            }

            public static string BuildPhoto(string source, string title = "photo", string href = "", int width = 0, int height = 0, bool mustThumb = true)
            {
                if (mustThumb && width > 0 && !source.StartsWith("http") && !source.Trim().ToLower().Equals("null"))
                {
                    source = height > 0 ? GetThumbImage_Zoom(source, width, height) : GetThumbImage_W(source, width);
                }
                return href.Equals("") ?
                    string.Format("<img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3}/>",
                    source,
                    HttpUtility.HtmlEncode(title),
                    width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                    height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty)
                    :
                 string.Format("<a title=\"{1}\" href=\"{4}\"><img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3}/></a>",
                    source,
                    HttpUtility.HtmlEncode(title),
                    width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                    height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty,
                    href);
            }

            public static string BuildPhoto(string source , string attribute, string attrValue, string title = "photo", string href = "", int width = 0, int height = 0, bool mustThumb = true, int w = 0, int h = 0)
            {
                if (mustThumb && width > 0 && !source.StartsWith("http"))
                {
                    source = height > 0 ? GetThumbImage_Zoom(source, width, height) : GetThumbImage_W(source, width);
                }
                return href.Equals("") ?
                    string.Format("<img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3} {4} {5} />",
                    source,
                    HttpUtility.HtmlEncode(title),
                    width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                    height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty,
                    w > 0 ? string.Format("w=\"{0}\"", w) : string.Empty,
                    h > 0 ? string.Format("h=\"{0}\"", h) : string.Empty)
                    :
                 string.Format("<a title=\"{1}\" href=\"{4}\" {5}><img itemprop=\"image\" src=\"{0}\" title=\"{1}\" alt=\"{1}\" {2} {3} {5} {6} {7} /></a>",
                    source,
                    HttpUtility.HtmlEncode(title),
                    width > 0 ? string.Format("width=\"{0}\"", width) : string.Empty,
                    height > 0 ? string.Format("height=\"{0}\"", height) : string.Empty,
                    href, string.IsNullOrEmpty(attribute) ? string.Empty : attribute + " = \"" + attrValue + "\"",
                    w > 0 ? string.Format("w=\"{0}\"", w) : string.Empty,
                    h > 0 ? string.Format("h=\"{0}\"", h) : string.Empty);
            }

        }

        public static string ListNewsIdToString(List<long> lst)
        {
            var result = new StringBuilder();
            int index = 0;
            foreach (var l in lst)
            {
                if(index == lst.Count)
                {
                    result.Append(l);
                    break;
                }
                result.AppendFormat("{0},", l);
                index++;
            }
            return result.ToString();
        }

        public static int GetMaxImageUploadFileSize()
        {
            return Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ImageUploadMaxSize"]);
        }

        public static string GenerateUserAvatarFileName(string UserName)
        {
            return "/UserFiles/UserAvatar/" + UserName + "/";
        }

        public static bool UseStorage()
        {
            if (System.Configuration.ConfigurationManager.AppSettings["UseStorage"] == "1") return true;
            else return false;
        }

        public static string CutEmail(object email)
        {
            string val = ConvertUtility.ConvertTo<string>(email);
            if (val.IndexOf("@") > -1)
            {
                val = val.Substring(0, val.IndexOf("@"));
            }
            return val;
        }

        public static string BuildFlash(string idFlash, string urlFlash, string urlData, int width, int height)
        {
            var flash = new StringBuilder();
            flash.AppendLine("<script type=\"text/javascript\">\n");
            flash.AppendFormat("var flashvars = {{xmlPath:\"{0}\"}};", urlData);
            flash.AppendLine("var params = {quality: \"high\",bgcolor: \"transparent\", play: \"true\", loop: \"true\", wmode: \"transparent\", scale: \"noscale\", menu: \"true\", devicefont: \"false\", salign: \"\", allowScriptAccess: \"sameDomain\"};");
            flash.AppendLine("var attributes = {name: \"" + idFlash + "\"};");
            flash.AppendFormat("swfobject.embedSWF(\"{0}\", \"{1}\", {2}, {3}, \"9.0.0\",\"\", flashvars, params, attributes);\n", urlFlash, idFlash, width, height);
            flash.AppendLine("</script>");
            return flash.ToString();
        }

        public static int GetSizePhoto(string size, bool isHeight = false)
        {
            if (string.IsNullOrWhiteSpace(size) || size.Contains("null")) return 0;
            var result = size.Split('x');
            return isHeight ? ConvertUtility.ConvertTo<int>(result[1]) : ConvertUtility.ConvertTo<int>(result[0]);
        }

        public static string GetFirstName(string name)
        {
            return name.Trim().Split(' ').Last();
        }
    }
}
